package com.bgdCA.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bgdCA.annotation.BiccAuth;
import com.bgdCA.domain.*;
import com.bgdCA.response.CodeMsg;
import com.bgdCA.response.Result;
import com.bgdCA.service.IFileInfoService;
import com.bgdCA.util.EasyExcelUtil;
import com.bgdCA.util.ExportExcel;
import com.bgdCA.util.StringUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Api(value = "档案信息管理", tags = "档案API")
@CrossOrigin
@Slf4j
@RequestMapping("/archives")
@RestController
public class FileInfoController {

    @Autowired
    private IFileInfoService dataService;

    @ApiOperation(value = "查询档案信息（支持分页）", notes = "查询档案信息（支持分页）")
    @RequestMapping(value = "/findAll", method = {RequestMethod.GET, RequestMethod.POST})
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result findAll(@ApiParam(value = "起始页(num>=0)", example = "1", required = true)
                          @RequestParam(defaultValue = "1") int pageNum,
                          @ApiParam(value = "查询数(默认10)", example = "10", required = false)
                          @RequestParam(defaultValue = "10") int pageSize) {
        log.debug("Controller");
        return dataService.findAll(pageNum, pageSize);
    }

    @ApiOperation(value = "查询单一档案信息", notes = "查询单一档案信息")
    @PostMapping("/findTarget")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result findTarget(@RequestBody int fileId) {
        log.debug("Controller:+" + fileId);
        return dataService.findTarget(fileId);
    }

    @ApiOperation(value = "更新档案信息", notes = "更新档案信息")
    @PostMapping("/updataFileInfo")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result updataFileInfo(@RequestBody FileInfo fileInfo) {
        log.debug("Controller:" + fileInfo.toString());
        return dataService.updataFileInfo(fileInfo);
    }

    @ApiOperation(value = "新增档案信息", notes = "新增档案信息")
    @PostMapping("/addFileInfo")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result addFileInfo(@RequestBody FileInfo fileInfo) {
        log.debug("Controller:" + fileInfo.toString());
        return dataService.addFileInfo(fileInfo);
    }

    @ApiOperation(value = "批量删除档案信息", notes = "批量删除档案信息")
    @PostMapping("/batchDeleteFileInfo")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result batchDeleteFileInfo(@RequestBody List<Integer> list) {
        log.debug("Controller:" + list.toString());
        return dataService.batchDeleteFileInfo(list);
    }

    @ApiOperation(value = "删除档案信息", notes = "删除档案信息")
    @PostMapping("/deleteFileInfo")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result deleteFileInfo(@RequestBody int fileId) {
        log.debug("Controller:" + fileId);
        return dataService.deleteFileInfo(fileId);
    }

    @ApiOperation(value = "【Excel】上传文件（返显数据）", notes = "【Excel】上传文件（返显数据）")
    @PostMapping(value = "/ReturnExcel")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result ReturnExcel(MultipartFile file) throws Exception {
        log.debug("Controller:" + file);
        List<FileInfoExcel> fileInfoList = new ArrayList();
        List<Object> list = EasyExcelUtil.readExcel(file, new FileInfoExcel(), 1, 1);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                //转换日期
                FileInfoExcel fileInfoExcel = (FileInfoExcel) o;
                fileInfoList.add(fileInfoExcel);
            }
            log.info("SaveExcel:" + fileInfoList.isEmpty());
        }
        /*相关dao和service已弃用 改为 读取*/
        return Result.success(fileInfoList);
    }

    @ApiOperation(value = "【Excel】筛选Excel导入", notes = "【Excel】筛选Excel导入")
    @PostMapping(value = "/SaveExcel")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result SaveExcel(@RequestBody List<FileInfoExcel> fileInfoExcel) throws Exception {
        log.debug("Controller:" + fileInfoExcel.isEmpty());
        return dataService.uploadExcel(fileInfoExcel);
    }

    @ApiOperation(value = "查询档案历史记录（支持分页）", notes = "查询档案历史记录（支持分页）")
    @RequestMapping(value = "/rebackAll", method = {RequestMethod.GET, RequestMethod.POST})
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result rebackAll(@ApiParam(value = "起始页(num>=0)", example = "1", required = true)
                            @RequestParam(defaultValue = "1") int pageNum,
                            @ApiParam(value = "查询数(默认10)", example = "10", required = false)
                            @RequestParam(defaultValue = "10") int pageSize) {
        log.debug("Controller");
        return dataService.rebackAll(pageNum, pageSize);
    }

    @ApiOperation(value = "数据分析", notes = "数据分析")
    @PostMapping("/dataAnalysis")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result dataAnalysis() {
        log.debug("Controller");
        return dataService.dataAnalysis();
    }

    @ApiOperation(value = "搜索匹配档案", notes = "搜索匹配档案")
    @PostMapping("/search")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result dataSearch(@RequestBody FileInfo fileInfo) {
        log.debug("Controller:+" + fileInfo);
        return dataService.datasearch(fileInfo);
    }

    @ApiOperation(value = "搜索匹配档案(分页)", notes = "搜索匹配档案（分页）")
    @PostMapping("/searchPage")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result dataSearchPage(@RequestBody FileInfo fileInfo) {
        log.debug("Controller:+" + fileInfo);
        return dataService.datasearchPage(fileInfo);
    }

    @ApiOperation(value = "档案全字段搜索", notes = "档案全字段搜索")
    @PostMapping("/searchAll")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    public Result dataSearchAll(@RequestBody String key) {
        log.debug("Controller:+" + key);
        return dataService.datasearchAll(key);
    }

    @ApiOperation(value = "数据分析2", notes = "数据分析2")
    @PostMapping("/dataAnalysis2")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    @ResponseBody
    public Result dataAnalysis2(@RequestBody FileInfo fileInfo) {
        log.debug("Controller");
        return dataService.dataAnalysis2(fileInfo);
    }

    @ApiOperation(value = "数据分析Plus", notes = "数据分析Plus")
    @PostMapping("/AnalysisPlus")
    @BiccAuth(auth = {AuthConstants.FileInfo})
    @ResponseBody
    public Result AnalysisPlus(@RequestBody FileInfo fileInfo) {
        log.debug("Controller");
        // TestForSearch testForSearch1 = new TestForSearch();
        //testForSearch1.setField("language");
        //System.out.println(a);
        return dataService.Analysisplus(fileInfo);
        //  return Result.success(null);
    }

    /*@ApiOperation(value = "导出匹配档案到Excel", notes = "导出匹配档案到Excel")
    @RequestMapping(value = "/exportFileInfoToExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @BiccAuth(auth = {AuthConstants.FileInfo})
    @ResponseBody
    public void exportFileInfoToExcel(@RequestBody FileInfo fileInfo,
                                      HttpServletResponse response) throws IOException{
        log.debug("Controller");

        try {
            dataService.exportFileInfoToExcel(fileInfo,response,"Analysis.xlsx");
        } catch (Exception e){
            e.printStackTrace();
        }

        //  return Result.success(null);
    }*/

    @ApiOperation(value = "导出匹配档案到Excel", notes = "导出匹配档案到Excel")
    @RequestMapping(value = "/fileInfoToExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @BiccAuth(auth = {AuthConstants.FileInfo})
    @ResponseBody
    public void fileInfoToExcel(@RequestBody FileInfoToExcel fileInfo
            , HttpServletRequest request, HttpServletResponse response) throws IOException{
        log.debug("Controller");
        List<FileInfoToExcel> list=dataService.fileInfoToExcel(fileInfo);
        List<Object[]> dataList = new ArrayList<Object[]>();
        HashMap<String,String> hashMap1=new HashMap<String,String>();
        FileInfoToExcel fileInfoToExcelText =list.get(0);
        int k=0;
        if(fileInfoToExcelText.getFileId()!=0 ){
            k++;
        }
        if(fileInfoToExcelText.getUserId()!=0 ){
            k++;
        }
        if(fileInfoToExcelText.getPersonalYear()!=0 ){
            k++;
        }
        if(fileInfoToExcelText.getLastName()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getFirstName()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getChineseName()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getIdNumber()!=null){
            k++;
        }
        if(fileInfoToExcelText.getContinent()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getNational()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getGender()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getBirthday()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getEntranceAge()!=0 ){
            k++;
        }
        if(fileInfoToExcelText.getReligion()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getCompany()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getChineseCompany()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getWorkDuty()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getChineseWorkDuty()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getLevel()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getTelephone()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getEmail()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getParticipateProject()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getStudyStart()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getStudyEnd()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getLanguage()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getDepartment()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getManager()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getChineseLevel()!=null ){
            k++;
        }
        if(fileInfoToExcelText.getRemarks()!=null ){
            k++;
        }
        for (int i = 0; i < list.size(); i++) {
            int j=0;
            Object[] objs = new Object[k];
            FileInfoToExcel fileInfoToExcel =list.get(i);
            if(fileInfoToExcel.getFileId()!=0 ){
                objs[j]=fileInfoToExcel.getFileId();
                j++;
                hashMap1.put("fileId","档案ID");
            }
            if(fileInfoToExcel.getUserId()!=0 ){
                objs[j]=fileInfoToExcel.getUserId();
                j++;
                hashMap1.put("userId","用户id");
            }
            if(fileInfoToExcel.getPersonalYear()!=0 ){
                objs[j]=fileInfoToExcel.getPersonalYear();
                j++;
                hashMap1.put("personalYear","年份");
            }
            if(fileInfoToExcel.getLastName()!=null ){
                objs[j]=fileInfoToExcel.getLastName();
                j++;
                hashMap1.put("lastName","姓");
            }
            if(fileInfoToExcel.getFirstName()!=null ){
                objs[j]=fileInfoToExcel.getFirstName();
                j++;
                hashMap1.put("firstName","名");
            }
            if(fileInfoToExcel.getChineseName()!=null ){
                objs[j]=fileInfoToExcel.getChineseName();
                j++;
                hashMap1.put("chineseName","中文名");
            }
            if(fileInfoToExcel.getIdNumber()!=null){
                objs[j]=fileInfoToExcel.getIdNumber();
                j++;
                hashMap1.put("idNumber","证件号");
            }
            if(fileInfoToExcel.getContinent()!=null ){
                objs[j]=fileInfoToExcel.getContinent();
                j++;
                hashMap1.put("continent","洲际");
            }
            if(fileInfoToExcel.getNational()!=null ){
                objs[j]=fileInfoToExcel.getNational();
                j++;
                hashMap1.put("national","国籍");
            }
            if(fileInfoToExcel.getGender()!=null ){
                objs[j]=fileInfoToExcel.getGender();
                j++;
                hashMap1.put("gender","性别");
            }
            if(fileInfoToExcel.getBirthday()!=null ){
                objs[j]=fileInfoToExcel.getBirthday();
                j++;
                hashMap1.put("birthday","生日");
            }
            if(fileInfoToExcel.getEntranceAge()!=0 ){
                objs[j]=fileInfoToExcel.getEntranceAge();
                j++;
                hashMap1.put("entranceAge","年龄");
            }
            if(fileInfoToExcel.getReligion()!=null ){
                objs[j]=fileInfoToExcel.getReligion();
                j++;
                hashMap1.put("religion","宗教");
            }
            if(fileInfoToExcel.getCompany()!=null ){
                objs[j]=fileInfoToExcel.getCompany();
                j++;
                hashMap1.put("company","工作单位");
            }
            if(fileInfoToExcel.getChineseCompany()!=null ){
                objs[j]=fileInfoToExcel.getChineseCompany();
                j++;
                hashMap1.put("chineseCompany","工作单位(中)");
            }
            if(fileInfoToExcel.getWorkDuty()!=null ){
                objs[j]=fileInfoToExcel.getWorkDuty();
                j++;
                hashMap1.put("workDuty","职务");
            }
            if(fileInfoToExcel.getChineseWorkDuty()!=null ){
                objs[j]=fileInfoToExcel.getChineseWorkDuty();
                j++;
                hashMap1.put("chineseWorkDuty","职务（中）");
            }
            if(fileInfoToExcel.getLevel()!=null ){
                objs[j]=fileInfoToExcel.getLevel();
                j++;
                hashMap1.put("level","级别");
            }
            if(fileInfoToExcel.getTelephone()!=null ){
                objs[j]=fileInfoToExcel.getTelephone();
                j++;
                hashMap1.put("telephone","电话");
            }
            if(fileInfoToExcel.getEmail()!=null ){
                objs[j]=fileInfoToExcel.getEmail();
                j++;
                hashMap1.put("email","邮箱");
            }
            if(fileInfoToExcel.getParticipateProject()!=null ){
                objs[j]=fileInfoToExcel.getParticipateProject();
                j++;
                hashMap1.put("participateProject","项目名");
            }
            if(fileInfoToExcel.getStudyStart()!=null ){
                objs[j]=fileInfoToExcel.getStudyStart();
                j++;
                hashMap1.put("studyStart","来BICC学习时间-起");
            }
            if(fileInfoToExcel.getStudyEnd()!=null ){
                objs[j]=fileInfoToExcel.getStudyEnd();
                j++;
                hashMap1.put("studyEnd","来BICC学习时间-止");
            }
            if(fileInfoToExcel.getLanguage()!=null ){
                objs[j]=fileInfoToExcel.getLanguage();
                j++;
                hashMap1.put("language","语言");
            }
            if(fileInfoToExcel.getDepartment()!=null ){
                objs[j]=fileInfoToExcel.getDepartment();
                j++;
                hashMap1.put("department","负责部门");
            }
            if(fileInfoToExcel.getManager()!=null ){
                objs[j]=fileInfoToExcel.getManager();
                j++;
                hashMap1.put("manager","班主任");
            }
            if(fileInfoToExcel.getChineseLevel()!=null ){
                objs[j]=fileInfoToExcel.getChineseLevel();
                j++;
                hashMap1.put("chineseLevel","汉语水平");
            }
            if(fileInfoToExcel.getRemarks()!=null ){
                objs[j]=fileInfoToExcel.getRemarks();
                j++;
                hashMap1.put("remarks","备注");
            }
            dataList.add(objs);
        }
        String[] rowsName = new String[hashMap1.size()];
        int i=0;
        for(String key:hashMap1.keySet()){
            rowsName[i]=hashMap1.get(key);
            i++;
        }

        String fileName = "fileInfoExport";

        //执行导出
        ExportExcel.exportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");


    }


}
